<template>
  <div class="review-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>我的评价</h3>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table :data="reviews" v-loading="loading" style="width: 100%">
        <el-table-column prop="reviewId" label="评论ID" width="100" />
        <el-table-column prop="productId" label="商品ID" width="100" />
        <el-table-column label="评分" width="180">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="comment" label="评论内容" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <!-- 编辑按钮 -->
            <el-button type="primary" link :icon="Edit" @click="openEditDialog(row)">编辑</el-button>
            <!-- 根据状态显示不同按钮 -->
            <el-button v-if="row.status === 1" type="danger" link :icon="Download" @click="handleWithdraw(row)">撤回</el-button>
            <el-button v-else type="success" link :icon="Upload" @click="handlePublish(row)">发布</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          style="margin-top: 20px;"
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="queryParams.pageSize"
          v-model:current-page="queryParams.page"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 编辑评论弹窗 -->
    <el-dialog v-model="editDialog.visible" title="编辑评论" width="500px" @close="editDialog.form = {}">
      <el-form :model="editDialog.form" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="editDialog.form.rating" show-score text-color="#ff9900" :max="5" />
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input v-model="editDialog.form.content" type="textarea" :rows="4" placeholder="请输入评论内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Upload, Download } from '@element-plus/icons-vue';
import { getUserReviews, updateReview, withdrawReview } from '@/api/review';

const loading = ref(true);
const reviews = ref([]);
const total = ref(0);
const queryParams = reactive({
  page: 1,
  pageSize: 10
});

// 编辑弹窗的数据模型
const editDialog = reactive({
  visible: false,
  form: {
    orderId: null,
    rating: 0,
    content: ''
  }
});

// 从后端获取评论列表
const fetchReviews = async () => {
  loading.value = true;
  try {
    const response = await getUserReviews(queryParams);
    if (response.code == 200) {
      reviews.value = response.data.list;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || '获取评论列表失败');
    }
  } catch (error) {
    console.error('获取评论列表异常:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 页面加载时执行
onMounted(fetchReviews);

// 分页变化时触发
const handlePageChange = (page) => {
  queryParams.page = page;
  fetchReviews();
};

// 打开编辑弹窗
const openEditDialog = (row) => {
  editDialog.form.orderId = row.orderId;
  editDialog.form.rating = row.rating;
  editDialog.form.content = row.comment; // 注意后端传来的字段可能是comment
  editDialog.visible = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  if (editDialog.form.rating === 0) {
    ElMessage.warning('请至少给出一星评分');
    return;
  }
  try {
    const res = await updateReview({
      orderId: editDialog.form.orderId,
      rating: editDialog.form.rating,
      content: editDialog.form.content
    });
    if (res.code == 200) {
      ElMessage.success('评论修改成功！');
      editDialog.visible = false;
      fetchReviews(); // 刷新列表
    } else {
      ElMessage.error(res.message || '修改失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，修改失败');
  }
};

// 处理撤回操作
const handleWithdraw = (row) => {
  ElMessageBox.confirm('确定要撤回这条评论吗？撤回后将不会公开显示。', '确认撤回', {
    type: 'warning'
  }).then(async () => {
    const res = await withdrawReview({ reviewId: row.reviewId });
    if (res.code == 200) {
      ElMessage.success('撤回成功！');
      fetchReviews();
    } else {
      ElMessage.error(res.message || '撤回失败');
    }
  }).catch(() => {});
};

// 处理发布操作
const handlePublish = (row) => {
  ElMessageBox.confirm('确定要发布这条评论吗？发布后将公开显示。', '确认发布', {
    type: 'primary'
  }).then(async () => {
    // 利用万能的submit接口来发布
    const res = await updateReview({
      orderId: row.orderId,
      rating: row.rating,
      content: row.comment
    });
    if (res.code == 200) {
      ElMessage.success('发布成功！');
      fetchReviews();
    } else {
      ElMessage.error(res.message || '发布失败');
    }
  }).catch(() => {});
};
</script>

<style lang="scss" scoped>
.review-container {
  padding: 20px;
}
</style>